package com.zxw.hotel.service.impl;

import com.zxw.hotel.dao.TotalDao;
import com.zxw.hotel.model.Total;
import com.zxw.hotel.service.TotalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
public class TotalServiceImpl implements TotalService {
    private TotalDao totalDao;
    @Autowired
    public void setTotalDao(TotalDao totalDao) {
        this.totalDao = totalDao;
    }
   public List<Total> findAll() {
        List<Total> all = totalDao.findAll();
        return all;
    }

    @Override
    public List<Total> selectquxain() {
       //获取当前时间的月份
        LocalDate now = LocalDate.now();
        //获得当前月的第一天
        LocalDate firstDayOfMonth = now.withDayOfMonth(1);
        //获得当前月的最后一天
        LocalDate lastDayOfMonth = now.withDayOfMonth(now.lengthOfMonth());
        //调用dao层的方法
        List<Total> totals = totalDao.selectquxain(firstDayOfMonth, lastDayOfMonth);
        // 查询数据库，获取当前月每天的统计数据
        for (LocalDate date = firstDayOfMonth; date.isBefore(lastDayOfMonth.plusDays(1)); date = date.plusDays(1)) {
            boolean found = false;
            for (Total total : totals) {
                if (total.getName().equals(date)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                totals.add(new Total(date.toString(), 0));
            }
        }
        // 对数据进行排序
        Collections.sort(totals, Comparator.comparing(Total::getName));
        //如果有重复的数据，将其合并
        for (int i = 1; i < totals.size(); i++) {
            if (totals.get(i).getName().equals(totals.get(i - 1).getName())) {
                totals.get(i - 1).setValue(totals.get(i - 1).getValue() + totals.get(i).getValue());
                totals.remove(i);
                i--;
            }
        }
        return totals;



    }
}
